package com.xj.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {

  //设置cookie的生命周期：7天
  private static int COOKIE_AGE = 60 * 60 * 24 * 7;

  /**
   * 将cookie信息写入浏览器的/目录下。本质是map
   * 使用response写入cookie
   * @param key
   * @param value
   * @param response
   */
  public static void writeCookie(String key, String value, HttpServletResponse response) {
    Cookie cookie = new Cookie(key, value);
    cookie.setPath("/");
    cookie.setMaxAge(COOKIE_AGE);
    response.addCookie(cookie);
  }

  /**
   * 将浏览器下存储的cookie去不读取出来，并查找是否有存在的
   * 使用request获取cookie
   * 这里只讨论get功能，不考虑过期
   *
   * @param key
   * @param request
   * @return
   */
  public static String getCookie(String key, HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (cookie.getName().equals(key)) {
          return cookie.getValue();
        }
      }
    }
    return null;
  }

  /**
   * 将浏览器中的之间key的素有cookie全部设置为“”,并设置最大时间为0，表示没有cookie
   * @param key
   * @param request
   * @param response
   */
  public static void removeCookie(String key, HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    int length=cookies == null ? 0 : cookies.length;

    for (int i = 0; i < length; i++) {
      if ((key).equalsIgnoreCase(cookies[i].getName())) {

        Cookie cookie = new Cookie(key, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);// 设置保存cookie最大时长为0，即使其失效
        response.addCookie(cookie);
      }
    }
  }

}
